package cn.gailvlun.gll.presentation.main;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;

import com.bumptech.glide.Glide;
import com.tencent.bugly.crashreport.CrashReport;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import cn.gailvlun.gll.BuildConfig;
import cn.gailvlun.gll.Constants;
import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.ChatClient2;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.chatlib.event.ReachabilityEvent;
import cn.gailvlun.gll.databinding.ActivityMainBinding;
import cn.gailvlun.gll.listener.ReachabilityReceiver;
import cn.gailvlun.gll.mgr.UploadMgr;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.presentation.apartment.ApartmentActivity;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.presentation.chat.DialogListActivity;
import cn.gailvlun.gll.presentation.chat.SilenceMemberActivity;
import cn.gailvlun.gll.presentation.emotion.EmotionSquareActivity;
import cn.gailvlun.gll.presentation.hotel.DayHotelActivity;
import cn.gailvlun.gll.presentation.hotel.NightHotelActivity;
import cn.gailvlun.gll.presentation.profile.ProfileActivity;
import cn.gailvlun.gll.presentation.wish.WishActivity;
import cn.gailvlun.gll.presentation.xroom.CrossRoomIntroduceActivity;
import cn.gailvlun.gll.util.DebugUtil;
import cn.gailvlun.gll.util.LogUtil;
import cn.gailvlun.gll.util.MeteoriteInterpolator;
import cn.gailvlun.gll.util.ProfileUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.functions.Consumer;

public class MainActivity extends BaseActivity {

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
    }

    public static void openActivity(Context context, boolean isFromLoginActivity) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("fromLogin", isFromLoginActivity);
        context.startActivity(intent);
    }

    public static void openActivity(Context context, boolean isFromLoginActivity, boolean clearOthers) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra("fromLogin", isFromLoginActivity);
        if (clearOthers) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        }
        context.startActivity(intent);
    }
    private ActivityMainBinding mBinding;
    private MainViewModel mViewModel;

    @Override
    protected void initComponent() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mBinding.setPresenter(new Presenter());

        ChatDB2.INSTANCE.setRealm();

        Glide.with(this)
                .load(R.drawable.img_bg_less)
                .into(mBinding.ivBackground);

        mViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        LogUtil.d("viewModel: " + mViewModel);
        mViewModel.getCountFlowable().subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                mBinding.tvMsg.setVisibility(integer != 0 ? View.VISIBLE : View.GONE);
                mBinding.tvMsg.setText(String.valueOf(integer));
            }
        });

        Profile profile = ProfileUtil.getProfile();
        if (profile != null) {
            ChatClient2.getInstance().connect();

            
            UploadMgr.init();

            uploadDeviceInfo();

            CrashReport.setUserId(String.valueOf(profile.getId()));
        } else {
            ToastUtil.showShort("信息错误，无法初始化聊天服务");
        }
    }

    private void uploadDeviceInfo() {
        String registrationId = JPushInterface.getRegistrationID(mContext);
        mViewModel.uploadDeviceInfo(registrationId);
    }

    @Override
    protected void createHandler() {
        shrinkViewClickRect(mBinding.ivEmotion);
    }

    private void shrinkViewClickRect(final View view) {
        mBinding.ivEmotion.post(new Runnable() {
            @Override
            public void run() {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mBinding.emotionHit.getLayoutParams();
                lp.height = mBinding.ivEmotion.getHeight() / 3 * 2;
                lp.width = mBinding.ivEmotion.getWidth();
                mBinding.emotionHit.setLayoutParams(lp);

                RelativeLayout.LayoutParams lp2 = (RelativeLayout.LayoutParams) mBinding.crossHit.getLayoutParams();
                lp2.height = mBinding.ivEmotion.getHeight() / 3;
                lp2.width = mBinding.ivEmotion.getWidth();
                mBinding.crossHit.setLayoutParams(lp2);
            }
        });

    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        mReachabilityReceiver = new ReachabilityReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        filter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
        filter.addAction("android.net.wifi.STATE_CHANGE");
        registerReceiver(mReachabilityReceiver, filter);
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        DebugUtil.debugTokenExpired(mContext,mBinding.getRoot());
    }
    public class Presenter {
        public void jump() {
            ApartmentActivity.openActivity(mContext);
        }

        public void onProfile() {
            ProfileActivity.openActivity(mContext);
        }

        public void onChat() {
            DialogListActivity.openActivity(mContext);
        }

        public void onCrossRoom() {
            CrossRoomIntroduceActivity.Companion.openActivity(mContext);
        }

        public void onEmotionMuseum() {
            EmotionSquareActivity.openActivity(mContext);
        }

        public void onInsomniaHotel() {
            if (BuildConfig.DEBUG) {
                int second = DateTime.now().getSecondOfMinute() % 2;
                if (second == 1) {
                    DayHotelActivity.Companion.openActivity(mContext);
                } else {
                    NightHotelActivity.Companion.openActivity(mContext);
                }
                return;
            }

            int hourOfDay = DateTime.now().withZone(DateTimeZone.forOffsetHours(8)).getHourOfDay();

            if (hourOfDay < 7 || hourOfDay >= 21) {
                NightHotelActivity.Companion.openActivity(mContext);
            } else {
                DayHotelActivity.Companion.openActivity(mContext);
            }
        }

        public void onWhateverHouse() {
            WishActivity.openActivity(mContext);
        }

        public void test() {


        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReachabilityEvent(ReachabilityEvent event) {
        if (event.status == ReachabilityReceiver.NOT_CONNECTED) {
            
            LogUtil.d("断网啦");
            ChatClient2.getInstance().disconnect();
        } else {
            
            LogUtil.d("有网啦");
            ChatClient2.getInstance().connect();
        }
    }

    private ReachabilityReceiver mReachabilityReceiver;

    @Override
    public void onBackPressed() {
        if (mViewModel.onBackPressed()) {
            super.onBackPressed();
        } else {
            ToastUtil.showShort("请在" + Constants.doubleClickDuration + "秒内再按一次返回键以退出程序");
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReachabilityReceiver);

        mViewModel.closeRealm();
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();

        Animation star1 = AnimationUtils.loadAnimation(mContext, R.anim.star_1);
        mBinding.ivStar1.startAnimation(star1);
        Animation star2 = AnimationUtils.loadAnimation(mContext, R.anim.star_2);
        mBinding.ivStar2.startAnimation(star2);
        Animation star3 = AnimationUtils.loadAnimation(mContext, R.anim.star_3);
        mBinding.ivStar3.startAnimation(star3);
        Animation star4 = AnimationUtils.loadAnimation(mContext, R.anim.star_4);
        mBinding.ivMedium.startAnimation(star4);

        mBinding.ivBig1.startAnimation(star1);
        mBinding.ivBig2.startAnimation(star2);

        Animation airplane = AnimationUtils.loadAnimation(mContext, R.anim.airplane);
        mBinding.ivAirplane.startAnimation(airplane);
        mBinding.ivCloud.startAnimation(airplane);

        Animation meteorite1 = AnimationUtils.loadAnimation(mContext, R.anim.meteorite_1);
        meteorite1.setInterpolator(new MeteoriteInterpolator());
        mBinding.ivMeteorite1.startAnimation(meteorite1);

        Animation meteorite2 = AnimationUtils.loadAnimation(mContext, R.anim.meteorite_2);
        meteorite2.setInterpolator(new MeteoriteInterpolator(-1));
        mBinding.ivMeteorite2.startAnimation(meteorite2);
    }

    @Override
    protected void onStop() {
        super.onStop();

        mBinding.ivStar1.clearAnimation();
        mBinding.ivStar2.clearAnimation();
        mBinding.ivStar3.clearAnimation();
        mBinding.ivMedium.clearAnimation();
        mBinding.ivBig1.clearAnimation();
        mBinding.ivBig2.clearAnimation();
        mBinding.ivAirplane.clearAnimation();
        mBinding.ivCloud.clearAnimation();
        mBinding.ivMeteorite1.clearAnimation();
        mBinding.ivMeteorite2.clearAnimation();
    }

    public static class Util {
        public static int getChatVisibility() {
            return View.VISIBLE;
        }
    }
}
